var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');//跨院资源共享

var app = express(); 

var usersRouter = require('./routes/users');
var indexRouter = require('./routes/index');

// 使用验证码校验
app.use(function (req, res, next) {
  let reqUrl = req._parsedUrl.pathname;
  console.log(reqUrl)
  let unCheckPath = [
    '/users/login',//备注
    '/email'
  ]
  if (!unCheckPath.includes(reqUrl)&&!reqUrl.includes("/public/images/") ) {
    let token = req.headers.token;
    if (token) {
      var jwt = new JwtUtil(token);
      var result = jwt.verifyToken();
    }
    // 如果考验通过就next，否则就返回登录信息不正确
    if (result == 'err' && token != undefined) {
      res.send({ status: 403, msg: '登录已过期,请重新登录' });
      // res.render('login.html');
    } else {
      // global.userInfo = result
      next();
    }
  } else {
    console.log(2);
    next();
  }
});
app.use('/users', usersRouter);
app.use('/', indexRouter);

// 请求图片资源
app.get('/public/images/*', function (req, res) {
  res.sendFile(__dirname + "/" + req.url);
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());//使用中间件
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  res.header('Access-Control-Allow-Credentials', 'true');
  next();
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

//捕捉错误信息
app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.send('资源路径不存在');
});

module.exports = app;
